package com.ruoyi.xzs.service.impl;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import org.springframework.util.StringUtils;
import com.ruoyi.xzs.domain.KnowsQuestion;
import com.ruoyi.xzs.domain.KnowsTree;
import com.ruoyi.xzs.domain.Question;
import com.ruoyi.xzs.domain.QuestionAnswer;
import com.ruoyi.xzs.enums.QuestionTypeEnum;
import com.ruoyi.xzs.excelTemplate.QuestionImportTemplate;
import com.ruoyi.xzs.mapper.KnowsQuestionMapper;
import com.ruoyi.xzs.mapper.KnowsTreeMapper;
import com.ruoyi.xzs.mapper.QuestionAnswerMapper;
import com.ruoyi.xzs.mapper.QuestionMapper;
import com.ruoyi.xzs.service.IQuestionService;
import com.ruoyi.xzs.vo.QuestionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 题库管理Service业务层处理
 * 
 * @author li
 * @date 2023-03-08
 */
@Service
public class QuestionServiceImpl implements IQuestionService 
{
    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private KnowsQuestionMapper knowsQuestionMapper;

    @Autowired
    private KnowsTreeMapper knowsTreeMapper;

    @Autowired
    private QuestionAnswerMapper questionAnswerMapper;

    /**
     * 查询题库管理
     * 
     * @param id 题库管理主键
     * @return 题库管理
     */
    @Override
    public Question selectQuestionById(Long id)
    {
        return questionMapper.selectQuestionById(id);
    }

    /**
     * 查询题库管理列表
     * 
     * @param question 题库管理
     * @return 题库管理
     */
    @Override
    public List<QuestionVO> selectQuestionList(Question question)
    {
        List<Question> questionList = questionMapper.selectQuestionList(question);
        List<QuestionVO> collect = questionList.stream().map(item -> {
            QuestionVO questionVO = new QuestionVO();
            BeanUtils.copyProperties(item, questionVO);
            for (QuestionTypeEnum value : QuestionTypeEnum.values()) {
                if (value.getCode() == item.getQuestionType()) {
                    questionVO.setQuestionName(value.getMsg());
                }
            }
            return questionVO;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 新增题库管理
     * 
     * @param question 题库管理
     * @return 结果
     */
    @Override
    public int insertQuestion(Question question)
    {
        question.setCreateTime(DateUtils.getNowDate());
        return questionMapper.insertQuestion(question);
    }

    /**
     * 修改题库管理
     * 
     * @param question 题库管理
     * @return 结果
     */
    @Override
    public int updateQuestion(Question question)
    {
        return questionMapper.updateQuestion(question);
    }

    /**
     * 批量删除题库管理
     * 
     * @param ids 需要删除的题库管理主键
     * @return 结果
     */
    @Override
    public int deleteQuestionByIds(Long[] ids)
    {
        return questionMapper.deleteQuestionByIds(ids);
    }

    /**
     * 删除题库管理信息
     * 
     * @param id 题库管理主键
     * @return 结果
     */
    @Override
    public int deleteQuestionById(Long id)
    {
        return questionMapper.deleteQuestionById(id);
    }

    /**
     * excel 题目导入数据 持久化到数据库
     * @param questionList
     * @param updateSupport
     * @param operName
     * @return
     */
    @Transactional
    @Override
    public String importUser(List<QuestionImportTemplate> questionList, boolean updateSupport, String operName) {

        if (questionList.size() <= 0 || questionList == null){
            throw new ServiceException("导入试题数据不能为空！");
        }

        // 查询所有题干
        List<String> questionStemsList = getQuestionList();

        // 根据题干去重
        List<QuestionImportTemplate> collect = questionList.stream().filter(item -> {
            // 过滤标志
            boolean flag = false;
            String qtrim = StringUtils.trimAllWhitespace(item.getQuestionStems());
            for (String stem : questionStemsList) {
                String trim = StringUtils.trimAllWhitespace(stem);
                if (trim.equals(qtrim)){
                    flag = true;
                }
            }
            return !flag;
        }).collect(Collectors.toList());

        if (collect == null){
            throw new ServiceException("当前导入的题目已存在");
        }

        // excel表格数据
        for (QuestionImportTemplate item : collect) {
            // 知识点编号不能为空
            Long knowId = item.getKnowId();
            if (knowId == null){
                throw new ServiceException("导入知识点编号不能为空，请点击《导出知识点》按钮查看！！！");
            }

            // 题目类型不能为空
            Long questionType = item.getQuestionType();
            if (questionType == null) {
                throw new ServiceException("导入题目类型不能为空");
            }

            // 题目分数不能为空
            Long score = item.getScore();
            if (score == null){
                throw new ServiceException("请设置题目分数");
            }

            // 知识点必须存在
            KnowsTree knowsTree = knowsTreeMapper.selectKnowsTreeById(knowId);
            if (null == knowsTree){
                throw new ServiceException("请输入正确的知识编号！！！");
            }

            // 试题--新增
            Long questionId = addQuestion(operName, item);

            // 知识点题目关联表--新增
            addKnowsPointQuestion(knowId, questionId);

            // 新增答案信息
            addQUestionAnswer(item, questionType, questionId);
        }

        return "恭喜您，数据已全部导入成功！";
    }

    /**
     * 新增题目
     * @param operName
     * @param item
     * @return
     */
    private Long addQuestion(String operName, QuestionImportTemplate item) {
        Question question = new Question();
        BeanUtils.copyProperties(item, question);
        question.setCreateUser(operName);
        question.setCreateTime(new Date());
        questionMapper.insertQuestion(question);
        Long questionId = question.getId();
        return questionId;
    }

    /**
     * 新增知识点关联题目信息
     * @param knowId
     * @param questionId
     */
    private void addKnowsPointQuestion(Long knowId, Long questionId) {
        KnowsQuestion knowsQuestion = new KnowsQuestion();
        knowsQuestion.setqId(questionId);
        knowsQuestion.setkId(knowId);
        knowsQuestionMapper.insertKnowsQuestion(knowsQuestion);
    }

    /**
     * 新增题目关联的答案信息
     * @param item
     * @param questionType
     * @param questionId
     */
    private void addQUestionAnswer(QuestionImportTemplate item, Long questionType, Long questionId) {
        String answer = item.getAnswer();
        QuestionTypeEnum[] values = QuestionTypeEnum.values();
        ArrayList<Long> longs = new ArrayList<Long>();
        for (int i = 0; i < values.length; i++) {
            longs.add((long) (i+1));
        }

        if (StringUtils.hasLength(answer) && longs.contains(questionType)) {
            QuestionAnswer questionAnswer = new QuestionAnswer();
            questionAnswer.setAnswer(answer);
            questionAnswer.setQuestionId(questionId);
            questionAnswerMapper.insertQuestionAnswer(questionAnswer);
        }
    }

    @Override
    public int selectCount() {
        questionMapper.selectCount();
        return 0;
    }

    /**
     *  查询所有的题目以及相关知识点
     *
     */
    private List<String> getQuestionList() {
        List<String> list = questionMapper.selectQuestionStems();
        return list;
    }
}
